/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;

/**
 * <p>Project: javaseapp - Ex5
 * <p>Powered by webrx On 2021-08-25 14:50:41
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 16
 */
public class Ex5 {
    volatile static Set<String> set = new HashSet<>();
    static CountDownLatch latch = new CountDownLatch(15);

    public static void work() {
        String tn = Thread.currentThread().getName();
        System.out.printf("%s:启动%n", tn);
        while (set.size() < 1) {
            try {
                TimeUnit.SECONDS.sleep(1);
                StringBuilder sbu = new StringBuilder("1");
                var rand = new Random();
                while (true) {
                    var op = List.of("", "+", "-");
                    for (int i = 2; i <= 9; i++) {
                        sbu.append(String.format("%s%d", op.get(rand.nextInt(op.size())), i));
                    }
                    String s = sbu.toString();
                    String st = s.replaceAll("(\\+|-)", ",$1");
                    Pattern pattern = Pattern.compile(",");
                    int sum = pattern.splitAsStream(st).map(Integer::parseInt).reduce(0, Integer::sum);
                    if (sum == 100) {
                        set.add(s);
                        break;
                    } else {
                        sbu.delete(1, sbu.length());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        latch.countDown();
    }

    public static void print() {
        String tn = Thread.currentThread().getName();
        System.out.printf("显示结果 %s:启动%n", tn);
        try {
            latch.await();
            System.out.println("5个线程已经结束，输出结果。");
            //System.out.println(set);
            AtomicInteger index = new AtomicInteger();
            set.forEach(e -> System.out.printf("%d、%s=100%n", index.incrementAndGet(), e));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 15; i++) {
            new Thread(Ex5::work, "T" + i).start();
        }

        new Thread(Ex5::print, "GameOver").start();
    }
}
